package com.example.systemserver.service;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWTUtil;
import com.example.systemserver.bean.AccountBean;
import com.example.systemserver.config.MyException;
import com.example.systemserver.dao.AccountMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AccountService {

    @Resource
    private AccountMapper accountMapper;

    public String login(AccountBean accountBean){
        log.debug("登录,检查参数");
        if (accountBean == null){
            throw new MyException("请输入用户名密码");
        }
        if (accountBean.getUsername() == null || accountBean.getUsername().trim().isEmpty()){
            throw new MyException("请输入用户名密码");
        }
        if (accountBean.getPassword() == null || accountBean.getPassword().trim().isEmpty()){
            throw new MyException("请输入用户名密码");
        }

        log.debug("登录,根据用户名查询数据");
        AccountBean beanQ = new AccountBean();
        beanQ.setUsername(accountBean.getUsername());
        AccountBean beanResult = accountMapper.info(beanQ);

        if (beanResult == null){
            throw new MyException("用户名密码错误");
        }

        log.debug("登录,检查密码");
        String password = DigestUtil.md5Hex(accountBean.getPassword());
        if (!beanResult.getPassword().equals(password)){
            throw new MyException("用户名密码错误");
        }
        log.debug("登录,返回结果");
        // 返回一个加密的字符串
        String token = JWTUtil.createToken(null, "123456".getBytes());
        return token;
    }

}
